/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xstgongyi.eduaid.common.PageHelper;
import org.xstgongyi.eduaid.dataobject.SponsorDO;
import org.xstgongyi.eduaid.manager.SponsorManager;
import org.xstgongyi.eduaid.bo.Gender;
import org.xstgongyi.eduaid.bo.SponsorType;

/**
 * @author oldcrane<br/>
 * @created 2019-04-17
 */
@Service
public class SponsorServiceImpl implements SponsorService {

	@Autowired
	private SponsorManager sponsorManager;

	@Override
	public void insert(SponsorDO sponsor) {

		if (null == sponsor.getAnonymous()) {
			sponsor.setAnonymous(false);
		}
		if (null == sponsor.getGender()) {
			sponsor.setGender(Gender.unknown);
		}
		if (null == sponsor.getType()) {
			sponsor.setType(SponsorType.unknown);
		}
		if (null == sponsor.getWaitPair()) {
			sponsor.setWaitPair(false);
		}
		if (null == sponsor.getWantVisit()) {
			sponsor.setWantVisit(false);
		}

		LocalDateTime now = LocalDateTime.now();
		sponsor.setGmtCreated(now);
		sponsor.setGmtUpdated(now);
		sponsorManager.insert(sponsor);
	}

	@Override
	public void update(SponsorDO sponsor) {
		sponsor.setGmtUpdated(LocalDateTime.now());
		sponsorManager.update(sponsor);
	}

	@Override
	public SponsorDO getById(Integer id) {
		SponsorDO sponsor = (null == id ? null : sponsorManager.getById(id));
		return sponsor;
	}

	@Override
	public List<SponsorDO> listAll() {
		return sponsorManager.listAll();
	}

	@Override
	public List<SponsorDO> listPage(String keyword, int pageNumber, int pageSize) {
		Map<String, Object> condition = new HashMap<>();
		pageNumber = pageNumber > 0 ? pageNumber : 1; // 缺省为第一页
		pageSize = pageSize > 0 ? pageSize : 20; // 缺省一页20条记录
		int offset = PageHelper.calcOffset(pageNumber, pageSize);
		condition.put("offset", offset);
		condition.put("limit", pageSize);
		keyword = null == keyword ? "" : keyword.trim();
		if (keyword.length() > 0) {
			condition.put("keyword", "%" + keyword + "%");
		}
		List<SponsorDO> sponsors = sponsorManager.listPage(condition);
		return sponsors;
	}

	@Override
	public int countTotal(String keyword) {
		Map<String, Object> condition = new HashMap<>();
		keyword = null == keyword ? "" : keyword.trim();
		if (keyword.length() > 0) {
			condition.put("keyword", "%" + keyword + "%");
		}
		return sponsorManager.countTotal(condition);
	}

}
